import os
import re

from mon_common import *
from mon_base import MonDaemonException

def get_xen_version():
    return xentop2list()['vmm_version']

def xentop2list():
    fd = os.popen('%s -b -d 1 -i 1' % xentop_path)
    
    general = fd.readline().split()
    if len(general) == 0:
        raise MonDaemonException, 'failed to exec xentop'
    fd.readline()
    memcpu = fd.readline().split()
    caps = fd.readline().split() 
    dom0detail = [i.strip() for i in re.split(r'(?<=[\w-]) +(?!limit)', \
                                      fd.readline())]
    domUdetails = [line.split() for line in fd]

    fd.close()

    result = {}
    result['vmm_version'] = general[-1]
    result['memtotal'] = memcpu[1]
    result['memused'] = memcpu[3]
    result['memfree'] = memcpu[5]
    result['dom0detail'] = dom0detail
    result['domUdetails'] = domUdetails

    return result

def get_total_domU_memory():
    domUs = xentop2list()['domUdetails']
    ret = 0
    for dom in domUs:
        ret += int(dom[4])

    return ret

if __name__ == '__main__':
    xentop2list()
